package com.liumingtai.learn.shiro.module.test01.controller;

import com.liumingtai.learn.shiro.module.test01.entity.BlogUser;
import com.liumingtai.learn.shiro.utils.CryptUtil;
import com.liumingtai.learn.shiro.utils.R;
import com.liumingtai.learn.shiro.utils.RedisUtil;
import com.liumingtai.learn.shiro.utils.TokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;

@RequestMapping("/shiro")
@RestController
public class ShiroController {
    @Autowired
    RedisUtil redisUtil;


    @GetMapping("/login")
    public R func() {
        return R.error(401, "请登录");
    }

    @PostMapping("/toLogin")
    public R toLogin(@RequestBody @Valid BlogUser user) {
        Subject subject = SecurityUtils.getSubject();
        String password = CryptUtil.getInstance().encryptAES(user.getPassword());
        AuthenticationToken token = new UsernamePasswordToken(user.getUserName(), password);
        try {
            subject.login(token);

            HashMap<String, Object> userMap = new HashMap<>();
            userMap.put("userName", user.getUserName());
            userMap.put("id", user.getId());
            userMap.put("password", password);

            String tokenStr = TokenUtil.createToken(userMap);
            redisUtil.hPut("shiroToken", tokenStr, userMap);
            return R.ok("登录成功").put("data", tokenStr);
        } catch (IncorrectCredentialsException ice) {
            return R.error(401, "用户名或密码不正确！");
        } catch (UnknownAccountException uae) {
            return R.error(401, "未知账户！");
        } catch (LockedAccountException lae) {
            return R.error(401, "账户已锁定！");
        } catch (ExcessiveAttemptsException eae) {
            return R.error(401, "用户名或密码错误次数太多！");
        } catch (AuthenticationException ae) {
            ae.printStackTrace();
            return R.error(401, "验证未通过！");
        } catch (Exception e) {
            return R.error(401, "验证未通过！");
        }
    }
}
